import { Form, Button, Input, message } from "antd";
import { useNavigate } from "react-router-dom";
import { login } from "../../api/login";
import "./index.css";

interface LoginUser {
    username: string;
    password: string;
}
const layoutCommon = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 }
}
const layoutBtn = {
    labelCol: { span: 0 },
    wrapperCol: { span: 24 }
}


export function Login() {
    const navigate = useNavigate();

    const onFinish = async (values: LoginUser) => {
        console.log(values);
        try {
            const resp: any = await login(values.username, values.password);
            console.log(resp);
            localStorage.setItem('token', resp.token);
            localStorage.setItem('userInfo', JSON.stringify(resp.user));
            navigate('/');
    
        } catch (error: any) {
            console.log(error);
            message.error(error?.data?.message || '系统繁忙请稍后重试');
        }
    }

    return <div className="login">
        <h1>聊天室</h1>
        <Form
            {...layoutCommon}
            colon={false}
            autoComplete="off"
            onFinish={onFinish}
        >
            <Form.Item label="用户名" name="username" rules={[{ required: true, message: '请输入用户名' }]}>
                <Input></Input>
            </Form.Item>
            <Form.Item label="密码" name="password" rules={[{ required: true, message: '请输入密码' }]}>
                <Input.Password></Input.Password>
            </Form.Item>

            <Form.Item {...layoutBtn}>
                <div className="login_links">
                    <a href="/register">创建账号</a>
                    <a href="/update_password">忘记密码</a>
                </div>
            </Form.Item>
            <Form.Item {...layoutBtn}>
                <Button className="login_btn" type="primary" htmlType="submit">登录</Button>
            </Form.Item>
        </Form>
    </div>
}